/*****************************************************************************
 * Copyright (C) Stacy Curl. All rights reserved.                            *
 * ------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the BSD      *
 * style license a copy of which has been included with this distribution in *
 * the LICENSE.txt file.                                                     *
 *****************************************************************************/
package picounit;

import java.lang.reflect.Constructor;

import junit.framework.Test;

public class StoryRunner implements StoryRunnerAPI {
	private StoryRunnerAPI implementation;
	
	public StoryRunner(String name) {
		this(name, getDefaultType());
	}

	public StoryRunner(String name, Class type) {
		implementation = createImplementation(name, type);
	}

	public Test generateJUnitTest() {
		return implementation.generateJUnitTest();
	}

	private static StoryRunnerAPI createImplementation(String name, Class type) {
		Class implementationClass = getImplementationClass();

		try {
			Constructor constructor = implementationClass.getConstructor(new Class[] {
				String.class, Class.class});

			return (StoryRunnerAPI) constructor.newInstance(new Object[] {name, type});
		}
		catch (Exception e) {
			throw new PicoUnitException(e);
		}
	}

	private static Class getImplementationClass() {
		return getClassProperty("picounit.storyrunner.implementation", "picounit.impl.StoryRunnerImpl");
	}

	private static Class getDefaultType() {
		return getClassProperty("picounit.default.test.type", "picounit.story.Story");
	}

	private static Class getClassProperty(String name, String defaultValue) {
		try {
			return Class.forName(System.getProperty(name, defaultValue));
		}
		catch (ClassNotFoundException classNotFoundException) {
			throw new PicoUnitException(classNotFoundException);
		}
	}
}
